package com.hugh.commom.netty.server.handle;

import com.alibaba.fastjson.JSON;

import com.hugh.commom.RpcRequest;
import com.hugh.commom.RpcResponse;
import com.hugh.commom.util.NetworkUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author gule
 */
@Slf4j
public class ServerProcessHandler extends SimpleChannelInboundHandler<RpcRequest> {

    private Map<String, Object> processMapping = new ConcurrentHashMap<String, Object>();

    public ServerProcessHandler(Map<String, Object> processMapping){
        this.processMapping = processMapping;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest requestMessage) throws Exception {
        log.info("OrderServerProcessHandler.channelRead0:{}", JSON.toJSON(requestMessage));

        //注意:  客户端将来发送请求的时候会传递一个参数:  UserService#sayHello#are you ok
        RpcResponse responseMessage = new RpcResponse();
        String className = requestMessage.getClassName();
        if(processMapping.containsKey(className)){
            Class<?> aClass = Class.forName(className);
            Method method = aClass.getMethod(requestMessage.getMethodName(), requestMessage.getParameterTypes());
            Object invoke = method.invoke(processMapping.get(className), requestMessage.getParameters());
            responseMessage.setResponse(invoke);
            responseMessage.setRequestId(requestMessage.getRequestId());
            String ipPort = NetworkUtils.getLocalIP() + ":" + NetworkUtils.getLocalPort();
            responseMessage.setIpPort(ipPort);
        }
        log.info("server处理完请求，响应结果是:{}", JSON.toJSON(responseMessage));
        if (ctx.channel().isActive() && ctx.channel().isWritable()) {
            ctx.writeAndFlush(responseMessage);
            log.info("OrderServerProcessHandler.ctx.writeAndFlush:{}", JSON.toJSON(responseMessage));
        } else {
            log.error("not writable now, message dropped");
        }
    }


}
